package com.guohong.service.impl;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.guohong.entity.UserRole;
import com.guohong.mapper.UserRoleMapper;
import com.guohong.service.UserRoleService;

@Service
public class UserRoleServiceImpl implements UserRoleService {
	@Autowired
	private UserRoleMapper userRoleMapper;

	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public void deleteByUserId(Long userId) {
		userRoleMapper.deleteByUserId(userId);
	}

	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public void saveOrUpdate(Long userId, String roleIds) {
		// 先删
		this.deleteByUserId(userId);
		
		if (StringUtils.isNotBlank(roleIds)) {
			String[] arr = roleIds.split(",");
			for (int i = 0; i < arr.length; i++) {
				UserRole userRole = new UserRole();
				userRole.setUserId(userId);
				userRole.setRoleId(Long.valueOf(arr[i]));
				
				// TODO
				userRole.setCreateUser("admin");
				userRole.setCreateTime(new Date());
				
				userRoleMapper.insert(userRole);
			}
		}
	}

}
